package com.lemons.hackaton.app.data;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.io.filefilter.WildcardFileFilter;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.lemons.hackaton.app.Application;
import com.lemons.hackaton.obj.Person;

public class QRDecoder {
	public String charset = "UTF-8";
	public Map<DecodeHintType, Object> aditionalQRInfo = new HashMap<DecodeHintType, Object>();
	
	
	
	public void processQRImages(String filePath) throws FileNotFoundException, NotFoundException, IOException {
		File dir = new File(filePath);
		FileFilter fileFilter = new WildcardFileFilter("*.png");
		File[] files = dir.listFiles(fileFilter);
		
		for(int i = 0; i < files.length; i++) {
			if(!files[i].toString().equals("") && files[i].toString() != null) {
				readQRCode(files[i].toString());
			}
		}
	}
	
	public String readQRCode(String filePath) throws FileNotFoundException, IOException, NotFoundException {

		try {
//			System.out.println("File -> " + filePath);
			aditionalQRInfo.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
			BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filePath)))));
			Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, aditionalQRInfo);
			parseQrString(qrCodeResult.getText());
			return qrCodeResult.getText();
		} catch (NotFoundException e) {
			System.out.println("Invalid File -> " + filePath);
			return "Invalid QR";
		}
	}
	
	public void parseQrString(String qrText) {
		
		Person p = new Person();
		String str = qrText.replace("\r", "").replace("\n", " ").trim();		
		String []pInfo  = str.split(" ");
		
		for (int i = 0; i < pInfo.length; i++) {
			try {
				switch(i) {
					case 0 : p = Application.journey.getPerson(pInfo[i]);
						break;
					case 1 :if(pInfo[i].startsWith("USD")){
							p.addToBudget(Float.valueOf(pInfo[i].replace("USD", "")));
						} else {
							p.setActivity(pInfo[i].toString().toLowerCase());
						}
						
						break;
					default: p.setActivity(pInfo[i].toString().toLowerCase());
					break;
				}
			} catch (NullPointerException e) {
				// TODO: handle exception
				continue;
			}
			
		}
	}
}
